// -------------------------------------------
// phpGMapTrips javascript functions 
// -------------------------------------------
ajaxCaller.shouldDebug = false;
ajaxCaller.shouldMakeHeaderMap = false;

var currentFile; // current file name
var currentTrip; // current trip name
var currentAPoint; // current point name

var editTripMode = false; // true if we are editing a trip
var editMode = false; // true if we are editing a point details
var hasToShowVisitor = false; // true it will show a point corresponding to the visitor IP address

var request; // XmlHttpRequest object for trips list
var requestTripPoints; // XmlHttpRequest object for trip points list

var trips = []; // trips list : key = trip name
var tripsSummary = []; // trips list : key = trip name
var tripsList = []; // trips list : key = trip order number
var tripPoints; // trip points list : key = point name
var tripOrderedPoints; // trip points list : key = sequence number
var tripOrderedPointsName; // trip points list : key = point name

var minTripSize = 100; // minimum size of trips
var maxTripSize = 0; // maximum size of trips

var tripcolors = ["000000", "003300", "330000", "333300", "660000", "663300", "990000", "993300", "cc0000", "cc3300", "ff0000", "ff3300"];

// select a point in the tool list and on the map
function selectPointName(name, zoomin) {
	if (name == undefined || name == "") {
		return;
	}
	showLoading();
	var apoint;
	if (currentAPoint != undefined) {
		// unshow point in point tool list
		apoint = document.getElementById("a_"+currentAPoint);
		try {
			apoint.style.backgroundColor = "white";
			// unshow point on map
			removeSelectPoint();
		} catch (erreur) {
		}
		try {
			unShowPointMapZoom();
		} catch (erreur) {
		}
	}


	try {
		selectPointNameMap(name, zoomin);
	} catch (erreur) {
		alert("name="+name+", erreur="+erreur);
	}

	// show point in point list
	currentAPoint = name;
	apoint = document.getElementById("a_"+currentAPoint);
	if (apoint != undefined) {
		apoint.style.backgroundColor = "lightgreen";
		// fill editzone
		var point = tripPoints[name];
		showPointDetails(point);
	}

  // remember back url
	if (StateManager != undefined) {
		var pageid = getPageId(currentFile, currentTrip, currentAPoint);
		var pagetitle = getPageTitle(currentFile, currentTrip, currentAPoint);
		StateManager.setState(pageid, pagetitle);
	}

	hideLoading();
}

function getShortCoord(coord){
	var parts = coord.split(".");
	if (parts.length>1) {
		return parts[0]+"."+parts[1].substr(0,2);
	}
	return coord;
}

function getPointDetails(point) {

       var result = "<div class='pointdetails' id='markerid_"+ point.getAttribute("name")+"' >";

	result += "<span class='placeTitle'>"+ point.getAttribute("title")+"</span>";
	result += "<br/>";


	var place = point.getElementsByTagName("place");
	if (place.length>1) {
		result += "<div class='pointplaces'>";
		result += getManyplaces(place);
		result += "</div>";
	} else {
		if (place[0].getAttribute("photoimg") != undefined && place[0].getAttribute("photoimg") != "") {
			result += "<div class='pointplaces'>";
			result += getOneplace(place[0], true);
			result += "</div>";
		} else {
			result += "<div class='pointplacesnoimg'>";
			result += getOneplace(place[0], true);
			result += "</div>";
		}
	}

	result += '<iframe id="editpointiframe" name="editpointiframename" ></iframe>';
	result += "</div>";
	var linktothispage = " <div id='pointtools'>";
	if (extramapsParams[ "editable"+currentFile] == undefined ||  extramapsParams[ "editable"+currentFile] == true) {
		linktothispage += '<a id="editcurrentpointlink" href="javascript:void(0);" onclick="editCurrentPoint(\''+point.getAttribute("name")+'\', currentOverlay);" title="'+lang_edit_place_link+'" ><img src="images/edit.gif" alt="'+lang_edit_place_link+'" /></a>'+' ';
	}
	linktothispage += "<a href='javascript:void(0);' title='"+lang_zoomin+"'  onclick='showClickedPoint(\""+point.getAttribute("name")+"\");'><img src='images/search.gif' alt='"+lang_zoomin+"' /></a>"+" ";
	linktothispage += "<a href='index.php?showfile="+escape(currentFile)+"&showtrip="+currentTrip+"&showpoint="+escape(point.getAttribute("name"))+"' title='"+lang_linktothistitle+"'><img src='images/link.gif' alt='"+lang_linktothistitle+"' /></a>"+" ";
	linktothispage += "<a href='http://maps.google.com/maps?hl=en&ll="+ point.getAttribute("lat")+","+ point.getAttribute("lng")+"&t=h&om=1' title='"+lang_googlemapstitle+"'><img src='images/map.gif' alt='"+lang_googlemapstitle+"' width='20px' /></a>"+" ";
	linktothispage += "<a href='http://maps.google.com/maps?hl=en&ll="+ point.getAttribute("lat")+","+ point.getAttribute("lng")+"&t=h&om=1&output=kml' title='"+lang_export_kml_link+"'><img src='images/google_earth_link.gif' width='18px' alt='"+lang_export_kml_link+"' /></a>"+" ";
	result += linktothispage;
	result += " "+"(";
	result += lang_destination_lat + " : "+ getShortCoord(point.getAttribute("lat"));
	result += ", ";
	result += lang_destination_long + " : "+ getShortCoord(point.getAttribute("lng"));
	result += ")";
	result += '</div>';
	return result;
}
function getOneplace(place, isAlone) {
	var result = "";
	var pmoreinfoStr = "";
	if (place.getAttribute("photoimg") != undefined && place.getAttribute("photoimg") != "") {
		result += "<a href='"+ unescape(place.getAttribute("url")) +"' ><img src='"+ place.getAttribute("photoimg")+ "' title='"+ place.getAttribute("title")+ "' /></a>";
	} else {
		if (!isAlone) {
			if (place.getAttribute("url") != undefined && place.getAttribute("url") != "") {
				result += "<a href='"+ unescape(place.getAttribute("url")) +"' >"+ place.getAttribute("title")+ "</a>";
			} else {
				result += place.getAttribute("title");
			}
		}
	}

	if (moreinfoNames.length >0) {
		result += "<div id='ppd"+place.getAttribute("name")+"' class='pointplacedesc'>";
		for (var i = 0; i < moreinfoNames.length; i++) {
			if (moreinfoNames[i] == "referer" && place.getAttribute(moreinfoNames[i]) != undefined) {
				pmoreinfoStr += moreinfoNamesLabel[moreinfoNames[i]] + " : <a href='"+ unescape(place.getAttribute(moreinfoNames[i])) +"'>"+ unescape(place.getAttribute(moreinfoNames[i])) +"</a><br/>";
			} else {
				if (place.getAttribute(moreinfoNames[i]) != undefined) {
					pmoreinfoStr += moreinfoNamesLabel[moreinfoNames[i]] + " : "+ unescape(place.getAttribute(moreinfoNames[i])) +"<br/>";
				}
			}
		}
		result += pmoreinfoStr;
		result += "</div>";
	}
	return result;
}
function getManyplaces(place) {
	var result = "";
	for (var j = 0; j < place.length; j++) {
		result += "<div class='pointplace'>";
		result += getOneplace(place[j], false);
		result += "</div>";
	}
	return result;
}
var previousCapId = "";
function showCaption(id) {
     if (previousCapId != "") {
         hideCaption(previousCapId);
     }
     var cap = document.getElementById("ppd"+id);
     if (cap != undefined) {
        cap.style.display = "block";
     }
     previousCapId = id;
}
function hideCaption(id) {

     var cap = document.getElementById("ppd"+id);
     if (cap != undefined) {
        cap.style.display = "none";
     }
}


function getAddPointDetails(point) {

       var result = "<div class='pointdetails' id='markerid_addpoint' >";

	result += "<span class='placeTitle'>"+ lang_add_place_link;+"</span>";
			result += "<div class='pointplacesnoimg'>";
			result += "</div>";
	result += '<iframe id="editpointiframe" name="editpointiframename" ></iframe>';
	result += "</div>";

	var linktothispage = " <div id='pointtools'>";
	if (extramapsParams[ "editable"+currentFile] == undefined ||  extramapsParams[ "editable"+currentFile] == true) {
	          linktothispage += '<a id="addpointlink" href="javascript:void(0);" onclick="editAddPoint(movedOverlayZoom);" ><img src="images/add.gif" /></a>'+' ';
	}
	linktothispage += "<a href='javascript:void(0);' title='"+lang_zoomin+"'  onclick='showClickedAddPoint(movedOverlayZoom);'><img src='images/search.gif' alt='"+lang_zoomin+"' /></a>"+" ";
	linktothispage += "<a href='http://maps.google.com/maps?hl=en&ll="+ point.y +","+ point.x +"&t=h&om=1' title='"+lang_googlemapstitle+"'><img src='images/map.gif' alt='"+lang_googlemapstitle+"' width='20px' /></a>"+" ";
	linktothispage += "<a href='http://maps.google.com/maps?hl=en&ll="+ point.y +","+ point.x +"&t=h&om=1&output=kml' title='"+lang_export_kml_link+"'><img src='images/google_earth_link.gif' width='18px' alt='"+lang_export_kml_link+"' /></a>"+" ";
	linktothispage += " "+"(";
	linktothispage += lang_destination_lat + " : "+ getShortCoord(""+point.y);
	linktothispage += ", ";
	linktothispage += lang_destination_long + " : "+ getShortCoord(""+point.x);
	linktothispage += ")";
	linktothispage += '</div>';
	result += linktothispage;
	return result;
}

// display trip edition zone
function editCurrentTrip() {
	editTripMode = true;
	toggleEditTrip(currentTrip);
}
// turns on/off trip edition zone
function toggleEditTrip(trip) {
	var piframe = document.getElementById("edittripiframe");
     if (piframe != undefined) {
	piframe.name = "edittripiframename";
	if (editTripMode) {
		piframe.src = "edittrip.php?file="+escape(currentFile)+"&langue="+escape(langue)+"&showtrip="+escape(trip)+"&nc="+Math.random();
		piframe.style.display = "block";
	} else {
		piframe.style.display = "none";
	}
     }
}


// display edition zone
function editCurrentPoint(apoint, overlay) {
	editMode = true;
	if(apoint == undefined) {
		apoint = currentAPoint;
	}
	toggleEditPoint(apoint, overlay);
}

// display add zone
function editAddPoint(overlay) {
	editMode = true;
	toggleEditPoint("new", overlay);
}

// turns on/off edition zone
function toggleEditPoint(point, overlay) {
	var piframe = document.getElementById("editpointiframe");
	piframe.name = "editpointiframename";
	if (editMode) {
		if (overlay != undefined) {
			var lat = 0;
			var lng = 0;
			if(mapProvider == "yahoo") {
			// todo	
			} else {
				lat = overlay.getPoint().y;
				lng = overlay.getPoint().x;
			}
			piframe.src = "editpoint.php?file="+escape(currentFile)+"&langue="+escape(langue)+"&showpoint="+escape(point)+"&showtrip="+escape(currentTrip)+"&lat="+escape(lat)+"&lng="+escape(lng)+"&nc="+Math.random();
		} else {
			piframe.src = "editpoint.php?file="+escape(currentFile)+"&langue="+escape(langue)+"&showpoint="+escape(point)+"&showtrip="+escape(currentTrip)+"&nc="+Math.random();
		}
/*
	var markerdiv = document.getElementById("markerid_"+point);
                markerdiv.style.backgroundColor="orange";
                markerdiv.style.height="130px";
*/
		piframe.style.display = "block";
	} else {
		piframe.style.display = "none";
	}
}

// show in point tool list, which point is clicked
function showClickedPoint(name, zoomin) {
        if (zoomin == undefined) {
           zoomin = true;
        }
	selectPointName(name, zoomin);
}
function showClickedAddPoint(overlay) {
	selectPointName(overlay.my_name, true);
}


var defaultFile; // temporary variable for use on ajax call back
var defaultTrip; // temporary variable for use on ajax call back
var defaultPoint; // temporary variable for use on ajax call back
var pointname; // temporary variable for use on ajax call back

// display trips list
function callTrips(adefaultFile, adefaultTrip, adefaultPoint) {
	defaultFile = adefaultFile;
	defaultTrip = adefaultTrip;
        defaultPoint = adefaultPoint;


   if (defaultFile == undefined) {
      defaultFile = "";
   }
   currentFile = defaultFile;
   showLoading();

  var url = "showtrips.php?file="+escape(defaultFile)+"&showtrip="+escape(defaultTrip);
  ajaxCaller.getXML(url, onTripsLoaded);
}

function getMenuSepar() {
	return "<hr/>";
}

function onTripsLoaded(xmlDoc, callingContext) {
	// once data is loaded, we process it
	trips = []; // trips list : key = trip name
	tripsList = []; // trips list : key = trip order number

	var menuelem = document.getElementById("menu");
	var tripsTag = xmlDoc.getElementsByTagName("trip");
	analyseTrips(tripsTag);
        var menucontent = "";
	menucontent += getCategories();
	menucontent += getMenuSepar();
        switchtogroups = 0;
	for (var i = 0; i < tripsTag.length; i++) {

		// load trips name
		var fw = getTripFontSize(eval(tripsTag[i].getAttribute("size")));
		var tripclass = "";
		if (tripsTag[i].getAttribute("g") == "t") {
			tripclass = " groupname";
                        switchtogroups++;
		}
		if (switchtogroups == 1) {
			menucontent += "<hr/>";
		}

		var triptitle = tripsTag[i].getAttribute("title");
		if (triptitle == undefined) {
			triptitle = tripsTag[i].getAttribute("name");
		}

		menucontent += "<a id='t_"+tripsTag[i].getAttribute("name")+"' href='javascript:void(0);' class='menuItem triplink"+tripclass+"' style='color:"+fw+";text-decoration:none;' onclick='callTrip(\"" + defaultFile + "\", \"" + tripsTag[i].getAttribute("name") + "\");' title='"+lang_trips_show_link+" " + tripsTag[i].getAttribute("name") + " "+"("+tripsTag[i].getAttribute("size")+")'>"+triptitle + "</a>"+" ";

		trips[tripsTag[i].getAttribute("name")] = tripsTag[i];
		tripsSummary[tripsTag[i].getAttribute("name")] = tripsTag[i];
		tripsList[i] = tripsTag[i].getAttribute("name");

	}

	var separelembody = "<a id='t_All' href='javascript:void(0);' class='menuItem triplink groupname' style='text-decoration:none;' onclick='callTrip(\"" + defaultFile + "\", \"All\");' title='"+lang_show_world_link+"'>"+lang_world_link+"</a>"+" ";
	if (defaultFile == "visitors") {
		separelembody += " <a id='t_Latest' href='javascript:void(0);' class='menuItem triplink groupname' style='text-decoration:none;' onclick='callTrip(\"" + defaultFile + "\", \"Latest\");' title='"+lang_show_latest_link+"'>"+lang_latest_link+"</a>"+" ";
	}
	menucontent += separelembody;
        menuelem.innerHTML = menucontent;

	// display first trip as default
	if (defaultTrip == undefined || defaultTrip == "") {
		var tmpdefaultTrip = extramapsParams["defaultTrip_"+defaultFile];
		if (tmpdefaultTrip == undefined || tmpdefaultTrip == "") {
			tmpdefaultTrip = default_trip;
		}
		if (tmpdefaultTrip != undefined && tmpdefaultTrip != "" && trips[tmpdefaultTrip] != undefined) {
			defaultTrip = tmpdefaultTrip;
		} else {
			if (tripsTag[0] != undefined) {
				defaultTrip = tripsTag[0].getAttribute("name");
			}
		}
	}
	if (trips[defaultTrip] == undefined) {
		if (tripsTag[0] != undefined) {
			alert("'"+defaultTrip +"' not found, showing '"+tripsTag[0].getAttribute("name")+"' !");
			defaultTrip = tripsTag[0].getAttribute("name");
		}
	}
	hideLoading();
	if (defaultTrip != undefined) {
	//alert("trips loaded calling trip "+defaultTrip);
		callTrip(defaultFile, defaultTrip, defaultPoint);
	}
}
function analyseTrips(tripsTag) {
	minTripSize = 100;
	maxTripSize = 0;
	for (var i = 0; i < tripsTag.length; i++) {
		var fw = eval(tripsTag[i].getAttribute("size"));
		if (fw < minTripSize) minTripSize = fw;
		if (fw > maxTripSize) maxTripSize = fw;
	}
//	alert("min="+minTripSize+" , max="+maxTripSize);
}
function getTripFontSize(nbPoints) {
	var min = 0;
	var max = tripcolors.length - 1;
	var rapport = (max-min) / (maxTripSize - minTripSize);
	var fw = Math.floor((nbPoints - minTripSize) * rapport) + min;
//	alert("nbpoints="+nbPoints+" -> fw="+fw);
	return "#"+tripcolors[fw];
}

function searchPoint(search) {
   callTrip(currentFile, "Search", "", search);
}
function showVisitor(showit) {
	hasToShowVisitor = showit;
	callTrip(currentFile, currentTrip, "", "");
}


// load trip points
function callTrip(adefaultFile, name, apointname, search) {
	defaultFile = adefaultFile;
	pointname = apointname;

	if (name == undefined || name == "") {
		return;
	}

	if (search == undefined) {
           search = "";
        }
	if (currentTrip != undefined) {
		// unshow trip in trip list
		atrip = document.getElementById("t_"+currentTrip);
		if (atrip != undefined) {
			atrip.style.backgroundColor = "white";
		}
	}
	currentTrip = name;

	// hide edit trip frame
	editTripMode =false;
	toggleEditTrip(currentTrip);

	// show trip in trips list
	//alert("tripid "+currentTrip);
	atrip = document.getElementById("t_"+currentTrip);
	if (atrip != undefined) {
		atrip.style.backgroundColor = "lightgreen";
	}

        showLoading();
  var url = "showtrippoints.php?file="+escape(defaultFile)+"&langue="+escape(langue)+"&showtrip="+escape(name)+"&search="+escape(search)+"&visitor="+escape(hasToShowVisitor)+"&nc="+new Date().getTime();
  ajaxCaller.getXML(url, onTripLoaded);


  // remember back url
	if (StateManager != undefined) {
	  var pageid = getPageId(currentFile, currentTrip, pointname);
	  var pagetitle = getPageTitle(currentFile, currentTrip, pointname);
	  StateManager.setState(pageid, pagetitle);
  }

}

function onTripLoaded(xmlDoc, callingContext) {
	// once data is loaded, we process it
	var tripsTag = xmlDoc.getElementsByTagName("trip");

	// if no points found, then reload all
	if(tripsTag == undefined || tripsTag.length == 0) {
		alert("'"+currentTrip+"' no place found, showing default trip !");
		callTrips(defaultFile, "", "");
	} else {
		for (var i = 0; i < tripsTag.length; i++) {
			// load trips name
			var tripname = tripsTag[i].getAttribute("name");
			trips[tripname] = tripsTag[i];

			var tripdata = tripsTag[i].getElementsByTagName("marker");
			if(tripdata == undefined || tripdata.length == 0) {
				alert("'"+tripname+"' no places found, showing default trip !");
				callTrips(defaultFile, "", "");
				break;
			}
			drawTrip(tripname, pointname);
			selectPointName(pointname);
		}
		hideLoading();
	}
}

function showLoading() {
   var loading = document.getElementById("loadingimg");
   if (loading != undefined) {
      loading.style.display = "block";
   }
}

function hideLoading() {
   var loading = document.getElementById("loadingimg");
   if (loading != undefined) {
      loading.style.display = "none";
   }
}
/* draggable stuff */

var dragobject={
z: 0, x: 0, y: 0, offsetx : null, offsety : null, targetobj : null, dragapproved : 0,
   initialize:function(){
	   document.onmousedown=this.drag;
	   document.onmouseup=function(){this.dragapproved=0};
   },
drag:function(e){
	     var evtobj=window.event? window.event : e;
	     this.targetobj=window.event? event.srcElement : e.target;
	     if (this.targetobj.className=="drag"){
		     this.dragapproved=1;
		     if (isNaN(parseInt(this.targetobj.style.left))){this.targetobj.style.left=0;}
		     if (isNaN(parseInt(this.targetobj.style.top))){this.targetobj.style.top=0;}
		     this.offsetx=parseInt(this.targetobj.style.left);
		     this.offsety=parseInt(this.targetobj.style.top);
		     this.x=evtobj.clientX;
		     this.y=evtobj.clientY;
		     if (evtobj.preventDefault){
			     evtobj.preventDefault();}
		     document.onmousemove=dragobject.moveit;
	     }
     },
moveit:function(e){
	       var evtobj=window.event? window.event : e;
	       if (this.dragapproved==1){
		       this.targetobj.style.left=this.offsetx+evtobj.clientX-this.x+"px";
		       this.targetobj.style.top=this.offsety+evtobj.clientY-this.y+"px";
		       return false;
	       }
       }
}; 

dragobject.initialize();
